package com.example.shop_2211.login

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.example.base.entity.LoginEntityResult
import com.example.base.entity.SendCodeEntityResult
import com.example.base.entity.UpdatePwdEntityResult
import com.example.base.mvvm.BaseViewModel
import com.google.gson.Gson
import kotlinx.coroutines.launch
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody

/**
 * 调用api中的方法，执行网络请求
 */
class LoginViewModel:BaseViewModel() {
    val sendCodeSuccess = MutableLiveData<SendCodeEntityResult>()//请求成功，包括响应码为200,300,400,500等情况
    val sendCodeFail = MutableLiveData<String>()//请求失败：有异常情况
    //发送验证码
    fun sendCode(phone:String){
        viewModelScope.launch {
            try {
                sendCodeSuccess.value = apiService.sendCode(phone)
            }catch (e:Exception){
                //请求失败
                sendCodeFail.value = e.message
            }
        }
    }
    //验证码登录
    val loginCodeSuccess = MutableLiveData<LoginEntityResult>()
    val loginCodeFail = MutableLiveData<String>()

    fun loginCode(phone:String,captcha:String){
        viewModelScope.launch {
            try {
                val map = mutableMapOf<String,String>()
                map.put("phone",phone)
                map.put("captcha",captcha)
                loginCodeSuccess.value = apiService.loginCode(mapToBody(map))//使用工具类
                //未使用工具类的调用
              /*  val json = Gson().toJson(map)
                val body = RequestBody.create("application/json;chatset=utf-8".toMediaTypeOrNull(),json)
                loginCodeSuccess.value = apiService.loginCode(body)*/
            }catch (e:Exception){
                loginCodeFail.value = e.message
            }
        }
    }
    //修改验证码
    val updatePwdSuccess = MutableLiveData<UpdatePwdEntityResult>()
    val updatePwdFail = MutableLiveData<String>()
    fun updatePwd(account:String,captcha:String,password:String){
        viewModelScope.launch {
            try {
                val map = mutableMapOf<String,String>()
                map.put("account",account)
                map.put("captcha",captcha)
                map.put("password",password)
                updatePwdSuccess.value = apiService.updatePwd(mapToBody(map))
            }catch (e:Exception){
                updatePwdFail.value = e.message
            }
        }
    }

    //密码登录
    val loginSuccess = MutableLiveData<LoginEntityResult>()
    val loginFail = MutableLiveData<String>()
    fun login(account:String,password:String){
        viewModelScope.launch {
            try {
                val map = mutableMapOf<String,String>()
                map["account"] = account
                map.put("password",password)
                loginSuccess.value = apiService.login(mapToBody(map))
            }catch (e:Exception){
                loginFail.value = e.message
            }
        }
    }

}